<?php

namespace App\Http\Controllers\Mini;

use App\Models\Activitys;
use App\Models\Ads;
use App\Models\Areas;
use App\Models\BidLists;
use App\Models\Cases;
use App\Models\Categorys;
use App\Models\Collections;
use App\Models\Footprints;
use App\Models\Orders;
use App\Models\Phonemap;
use App\Models\Services;
use App\Models\SignUps;
use App\Models\StoreEvaluates;
use App\Models\Stores;
use App\Models\UserInfos;
use App\Models\Users;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Pagination\LengthAwarePaginator;

class StoreController extends Controller
{
    /**
     * 供应商分类
     * @route api.store.storeCate
     */
    public function storeCate(Request $request){
        try{
            $lists = Categorys::getCascaderList();
            $fields = ['id','store_name','logo','call','view','credit','hot','quality','cate_id'];
            foreach ($lists as $k=>$v){//获取分类下的商铺
                $cid = $v['value'];
                $lists[$k]['store'] = Stores::where('status',1)->where('status','<>',-1)
                    ->where('index_recomment',$cid)->orwhere('index_spare',$cid)
                    ->orderBy('index_recomment', 'desc')
                    ->limit(4)->get($fields);
                foreach ($lists[$k]['store'] as $kk=>$vv){
                    $lists[$k]['store'][$kk]['view'] = strlen($vv['view'])>=4 ? '999+' : $vv['view'];
                    $lists[$k]['store'][$kk]['call'] = strlen($vv['call'])>=4 ? '999+' : $vv['call'];
                    //擅长领域
                    if (!empty($vv['cate_id'])){
                        $cate_id = explode(',',$vv['cate_id']);
                        foreach ($cate_id as $kkk => $vvv){
                            $pidTree[] = Categorys::where(['id'=>$vvv])->first('name');
                        }
                    }else{
                        $pidTree['name'] = [];
                    }
                    $lists[$k]['store'][$kk]['cate_name'] = $pidTree;
                    $pidTree = [];
                }
                //获取分类下的广告
                $params = [
                    'adsense_id' => 34,
                    'status' => 1,
                ];
                $lists[$k]['adv'] = Ads::getList($params, ['id','adsense_id','thumb','link','target']);
            }

            return response()->json([
                "code" => 1,
                "msg" => "获取成功",
                "data" => $lists
            ]);
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

    /**
     * 供应商筛选
     * @route api.store.storeScreen
     */
    public function storeScreen(Request $request){
        try{
            $lists = [];
            $lists['cate'] = Categorys::getCascaderList();
            $lists['area'] = Areas::where('status','<>',-1)->orderBy('sort','asc')->get(['id','name']);//服务区域

            return response()->json([
                "code" => 1,
                "msg" => "获取成功",
                "data" => $lists
            ]);
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

    /**
     * 供应商列表
     * @route api.store.storeLists
     * @param content 搜索词条
     * @param cid_pid 一级分类id
     * @param cid_id 二级分类id
     * @param area 区域id
     * @param page 页码
     * @param limit 条数
     * @param sid 排序 1成交量 2浏览量 3好评量
     */
    public function storeLists(Request $request){
        try{
            $map = [
                'keyword' => $request->post('content'),//搜索词条
                'cid_pid' => $request->post('cid_pid'),//一级分类id
                'cid_id' => $request->post('cid_id'),//二级分类id
                'area' => $request->post('area'),//区域id
            ];
            $page = (int)$request->post('page',1);//页码
            $limit = (int)$request->post('limit',5);//条数
            $sid = (int)$request->post('sid');//排序 1来电量 2浏览量 3好评量 4成交量 不传或其他：全部
            if ($sid == 1){
                $sort = 'call';
            }elseif ($sid == 2){
                $sort = 'view';
            }elseif ($sid == 3){
                $sort = 'credit';
            }elseif ($sid == 4){
                $sort = 'service';
            }else{
                $sort = 'created_at';
            }
            $fields = ['id','user_id','store_name','logo','call','view','service','credit','hot','quality','cate_id'];
            $lists = Stores::webLists($map, $fields, $page, $limit, $sort, 'desc');
            foreach ($lists as $key=>$val){
                $lists[$key]['view'] = strlen($val['view'])>=4 ? '999+' : $val['view'];
                $lists[$key]['call'] = strlen($val['call'])>=4 ? '999+' : $val['call'];
                $lists[$key]['service'] = strlen($val['service'])>=4 ? '999+' : $val['service'];
                $lists[$key]['master_name'] = UserInfos::where('user_id',$val['user_id'])->value('master_name');
                $lists[$key]['master_phone'] = Users::where('id',$val['user_id'])->value('mobile');
                //擅长领域
                if (!empty($val['cate_id'])){
                    $cate_id = explode(',',$val['cate_id']);
                    foreach ($cate_id as $k => $v){
                        $pidTree[] = Categorys::where(['id'=>$v])->first('name');
                    }
                }else{
                    $pidTree['name'] = [];
                }
                $lists[$key]['cate_name'] = $pidTree;
                $pidTree = [];
            }
            return response()->json([
                "code" => 1,
                "msg" => "获取成功",
                "data" => $lists
            ]);
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

    /**
     * 供应商详情-基本信息
     * @route api.store.storeDetails
     * @param user_id 用户id
     * @param store_id 供应商id
     * @return is_collect 0:未收藏 1:已收藏
     */
    public function storeDetails(Request $request){
        try{
            $user_id = (int)$request->post('user_id');
            $user_info = Users::where('id',$user_id)->where('status','<>',-1)->first();

            $store_id = (int)$request->post('store_id');//供应商id
            $seller_id = Stores::where('id',$store_id)->value('user_id');//当前店铺主人id
            if (empty($store_id) || empty($seller_id)) return response()->json(["code"=>0, "msg"=>'参数错误']);

            $fields = ['id','user_id','store_name','logo','banner','hot','quality','area_info','workingtime','view','call','credit','cate_id','description'];
            $lists = Stores::details(['id'=>$store_id], $fields);
            $lists['master_name'] = UserInfos::where('user_id',$lists['user_id'])->value('master_name');//联系人姓名
            $lists['master_phone'] = Users::where('id',$lists['user_id'])->value('mobile');//联系人电话
            $lists['call'] = strlen($lists['call'])>=4 ? '999+' : $lists['call'];
            //二级分类
            if (!empty($lists['cate_id'])){
                $lists['cate_id'] = explode(',',$lists['cate_id']);
                foreach ($lists['cate_id'] as $k => $v){
                    $pidTree[] = Categorys::where('id',$v)->first('name');
                }
            }else{
                $pidTree['name'] = [];
            }
            $lists['cate_id'] = $pidTree;
            //判断是否收藏
            $lists['is_collect'] = 0;//默认未收藏
            if (!empty($user_info)){
                if ($user_info['type'] == 1){
                    $collect = Collections::where(['collect_id'=>$store_id,'user_id'=>$user_info['id'],'type'=>4])->value('collect_id');
                    $lists['is_collect'] = empty($collect) ? 0 : 1;
                }
                //添加足迹
                $foot_arr = [
                    'user_id' => $user_info['id'],
                    'foot_id' => $store_id,
                    'type'    => 1,
                ];
                $foot_id = Footprints::where($foot_arr)->value('id');
                if($foot_id > 0){
                    Footprints::where($foot_arr)->update(['updated_at'=>date('Y-m-d H:i:s')]);
                }else{
                    Footprints::create($foot_arr);
                }
            }
            Stores::where('id',$store_id)->increment('view');//浏览量加1

            return response()->json([
                "code" => 1,
                "msg" => "获取成功",
                "data" => $lists
            ]);
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

    /**
     * 供应商图片
     * @route api.store.storeImg
     * @param store_id 供应商id
     * @param page 页码
     * @param limit 条数
     * @return bool
     */
    public function storeImg(Request $request){
        try{
            $store_id = (int)$request->post('store_id');//供应商id
//            $page = (int)$request->post('page',1);//页码
//            $limit = (int)$request->post('limit',4);//条数
//            if (empty($store_id) || empty($page) || empty($limit)) return response()->json(["code"=>0, "msg"=>'参数错误']);
            if (empty($store_id)) return response()->json(["code"=>0, "msg"=>'参数错误']);
            $lists = Stores::details(['id'=>$store_id],'image');

//            //计算每页分页的初始位置
//            $offset = ($page * $limit) - $limit;
//            //实例化LengthAwarePaginator类，并传入对应的参数
//            if(!empty($lists['image'])){
//                $res = new LengthAwarePaginator(
//                    array_slice($lists['image'], $offset, $limit, false),
//                    count($lists['image']),
//                    $limit, $page,
//                    ['path' => $request->url(), 'query' => $request->query()]
//                );
//            }else{
//                $res = new LengthAwarePaginator(
//                    array_slice([], $offset, $limit, false),
//                    count([]),
//                    $limit, $page,
//                    ['path' => $request->url(), 'query' => $request->query()]
//                );
//            }

            return response()->json([
                "code" => 1,
                "msg" => "获取成功",
                "data" => $lists
            ]);
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

    /**
     * 供应商合作伙伴
     * @route api.store.storePartners
     * @param store_id 供应商id
     * @param page 页码
     * @param limit 条数
     * @return bool
     */
    public function storePartners(Request $request){
        try{
            $store_id = (int)$request->post('store_id');//供应商id
//            $page = (int)$request->post('page',1);//页码
//            $limit = (int)$request->post('limit',4);//条数
//            if (empty($store_id) || empty($page) || empty($limit)) return response()->json(["code"=>0, "msg"=>'参数错误']);
            if (empty($store_id)) return response()->json(["code"=>0, "msg"=>'参数错误']);
            $lists = Stores::details(['id'=>$store_id],'partners');

//            //计算每页分页的初始位置
//            $offset = ($page * $limit) - $limit;
//            //实例化LengthAwarePaginator类，并传入对应的参数
//            if(!empty($lists['partners'])){
//                $res = new LengthAwarePaginator(
//                    array_slice($lists['partners'], $offset, $limit, false),
//                    count($lists['partners']),
//                    $limit, $page,
//                    ['path' => $request->url(), 'query' => $request->query()]
//                );
//            }else{
//                $res = new LengthAwarePaginator(
//                    array_slice([], $offset, $limit, false),
//                    count([]),
//                    $limit, $page,
//                    ['path' => $request->url(), 'query' => $request->query()]
//                );
//            }

            return response()->json([
                "code" => 1,
                "msg" => "获取成功",
                "data" => $lists
            ]);
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

    /**
     * 供应商服务
     * @route api.store.storeService
     * @param store_id 供应商id
     * @param page 页码
     * @param limit 条数
     */
    public function storeService(Request $request){
        try{
            $store_id = (int)$request->post('store_id');//供应商id
            $page = (int)$request->post('page',1);//页码
            $limit = (int)$request->post('limit',4);//条数
            if (empty($store_id) || empty($page) || empty($limit)) return response()->json(["code"=>0, "msg"=>'参数错误']);
            $lists = Services::allLists(['store_id'=>$store_id],['id','store_id','thumb','title','content'], $page, $limit);

            return response()->json([
                "code" => 1,
                "msg" => "获取成功",
                "data" => $lists
            ]);
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

    /**
     * 供应商服务详情
     * @route api.store.storeServiceDetails
     * @param cases_id 服务id
     */
    public function storeServiceDetails(Request $request){
        try{
            $service_id = (int)$request->post('service_id');//服务id
            if (empty($service_id)) return response()->json(["code"=>0, "msg"=>'参数错误']);
            $lists = Services::details(['id'=>$service_id]);

            return response()->json([
                "code" => 1,
                "msg" => "获取成功",
                "data" => $lists
            ]);
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

    /**
     * 供应商案例
     * @route api.store.storeCases
     * @param store_id 供应商id
     * @param page 页码
     * @param limit 条数
     */
    public function storeCases(Request $request){
        try{
            $store_id = (int)$request->post('store_id');//供应商id
            $page = (int)$request->post('page',1);//页码
            $limit = (int)$request->post('limit',4);//条数
            if (empty($store_id) || empty($page) || empty($limit)) return response()->json(["code"=>0, "msg"=>'参数错误']);
            $lists = Cases::allLists(['store_id'=>$store_id], ['*'], $page, $limit);

            return response()->json([
                "code" => 1,
                "msg" => "获取成功",
                "data" => $lists
            ]);
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

    /**
     * 供应商案例详情
     * @route api.store.storeCasesDetails
     * @param cases_id 案例id
     * @return bool
     */
    public function storeCasesDetails(Request $request){
        try{
            $cases_id = (int)$request->post('cases_id');//案例id
            if (empty($cases_id)) return response()->json(["code"=>0, "msg"=>'参数错误']);
            $lists = Cases::details(['id'=>$cases_id]);

            return response()->json([
                "code" => 1,
                "msg" => "获取成功",
                "data" => $lists
            ]);
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

    /**
     * 供应商评价
     * @route api.store.storeEvaluateLists
     * @param store_id 供应商id
     * @param page 页码
     * @param limit 条数
     */
    public function storeEvaluateLists(Request $request){
        try{
            $store_id = (int)$request->post('store_id');//供应商id
            $page = (int)$request->post('page',1);//页码
            $limit = (int)$request->post('limit',4);//条数
            if (empty($store_id) || empty($page) || empty($limit)) return response()->json(["code"=>0, "msg"=>'参数错误']);
            $map = [
                'store_id' => $store_id,
                'evaluates_type' => (int)$request->post('evaluates_type',1),//1:好评 2：中评 3：差评
            ];
            $lists = StoreEvaluates::allLists($map,['user_name','user_avatar','content','average_star','type','created_at'],$page,$limit);
            foreach ($lists as $k=>$v){
                $lists[$k]['user_name'] = '**'.mb_substr($v['user_name'],-2,4,"utf-8");
            }
            $sum = StoreEvaluates::counts(['store_id'=>$store_id]);//总评论数
            $good = StoreEvaluates::counts(['store_id'=>$store_id,'type'=>1]);//好评数
            $speed = StoreEvaluates::sums(['store_id'=>$store_id], 'speed');
            $quality = StoreEvaluates::sums(['store_id'=>$store_id], 'quality');
            $attitude = StoreEvaluates::sums(['store_id'=>$store_id], 'attitude');
            $store['sum'] = $sum;//评价总数
            $store['avg_good'] = empty($sum) ? 100 : intval(round (($good/$sum)*100));//好评率
            $store['avg_speed'] = empty($sum) ? 5 : intval(round ($speed/$sum));//平均工作速度
            $store['avg_quality'] = empty($sum) ? 5 : intval(round ($quality/$sum));//平均工作质量
            $store['avg_attitude'] = empty($sum) ? 5 : intval(round ($attitude/$sum));//平均工作态度
            $middle = StoreEvaluates::counts(['store_id'=>$store_id,'type'=>2]);//中评数
            $bad = StoreEvaluates::counts(['store_id'=>$store_id,'type'=>3]);//差评数

            $store['good'] = strlen($good)>=4 ? '999+' : $good;//好评数
            $store['middle'] = strlen($middle)>=4 ? '999+' : $middle;
            $store['bad'] = strlen($bad)>=4 ? '999+' : $bad;

            $evaluate['list'] = $lists;
            $evaluate['store'] = $store;

            return response()->json([
                "code" => 1,
                "msg" => "获取成功",
                "data" => $evaluate
            ]);
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

    /**
     * 供应商收藏
     * @route api.store.storeCollect
     * @param user_id 用户id
     * @param collect_id 收藏内容id
     */
    public function storeCollects(Request $request){
        try{
            $user_id = (int)$request->post('user_id');
            if (empty($user_id)) return response()->json(["code"=>0, "msg"=>'请先登录']);
            $userinfo = Users::where(['id'=>$user_id])->where('status','<>',-1)->first(['type','status']);
            if (empty($userinfo)){
                return response()->json(["code"=>0, "msg"=>'用户不存在,请联系客服!']);
            }else{
                if($userinfo['status'] == 2){
                    return response()->json(["code"=>0, "msg"=>'账户正在审核中，请等待审核!']);
                }elseif($userinfo['status'] == 3){
                    return response()->json(["code"=>0, "msg"=>'账号未通过审核，请前往个人中心查看原因并重新提交审核!']);
                }elseif ($userinfo['status'] == 4){
                    return response()->json(["code"=>0, "msg"=>'账号已锁定，请前往个人中心查看原因或联系客服!']);
                }
                if ($userinfo['type'] != 1) return response()->json(["code"=>0, "msg"=>'供应商不能收藏店铺!']);
            }

            $collect_id = (int)$request->post('collect_id');
            if (empty($collect_id)) return response()->json(["code"=>0, "msg"=>'参数错误']);
            $collect = Collections::where(['collect_id'=>$collect_id, 'user_id'=>$user_id, 'type'=>4])->value('id');
            if (empty($collect)){
                $params = [
                    'collect_id' => $collect_id,
                    'user_id' => $user_id,
                    'collect_at' => date('Y-m-d H:i:s'),
                    'type' => 4,
                ];
                Collections::create($params);
                Stores::where('id',$collect_id)->increment('collections');
                return response()->json(["code"=>1, "msg"=>'收藏成功']);
            }else {
                Collections::where(['collect_id'=>$collect_id, 'user_id'=>$user_id, 'type'=>4])->delete();
                return response()->json(["code"=>1, "msg"=>'取消收藏成功']);
            }
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

    /**
     * 供应商评价
     * @route api.store.storeEvaluates
     * @param user_id 用户id
     * @param store_id 店铺id
     * @param content 评价内容
     * @param speed 速度
     * @param quality 质量
     * @param attitude 态度
     */
    public function storeEvaluates(Request $request){
        try{
            $user_id = (int)$request->post('user_id');
            if (empty($user_id)) return response()->json(["code"=>0, "msg"=>'请先登录']);
            $userinfo = Users::where(['id'=>$user_id])->where('status','<>',-1)->first(['username','avatar','type','status']);
            if (empty($userinfo)){
                return response()->json(["code"=>0, "msg"=>'用户不存在,请联系客服!']);
            }else{
                if($userinfo['status'] == 2){
                    return response()->json(["code"=>0, "msg"=>'账户正在审核中，请等待审核!']);
                }elseif($userinfo['status'] == 3){
                    return response()->json(["code"=>0, "msg"=>'账号未通过审核，请前往个人中心查看原因并重新提交审核!']);
                }elseif ($userinfo['status'] == 4){
                    return response()->json(["code"=>0, "msg"=>'账号已锁定，请前往个人中心查看原因或联系客服!']);
                }
                if ($userinfo['type'] != 1) return response()->json(["code"=>0, "msg"=>'供应商不能评价供应商!']);
            }

            $store_id = (int)$request->post('store_id');
            $gys_user_id = Stores::where('id',$store_id)->where('status','<>',-1)->value('user_id');//当前店铺用户id
            //判断是否购买商品
            $order = Orders::where(['user_id'=>$user_id,'store_id'=>$store_id,'pay_status'=>2])->pluck('id');
            //判断是否投标
            $bid = BidLists::where(['user_id'=>$user_id,'store_id'=>$gys_user_id])->pluck('id');
            //判断是否有拨打电话
            $gys_mobile = Users::where('id',$gys_user_id)->where('status','<>',-1)->value('mobile');
            $phone = Phonemap::where(['anumber'=>$userinfo['mobile'],'bnumber'=>$gys_mobile,'status'=>1])->where('connet_status','<>',0)->pluck('id');
            //判断是否报名活动
            $act_ids = Activitys::where('user_id',$gys_user_id)->where('status','<>',-1)->pluck('id');
            if (!$act_ids->isEmpty()){
                $sign = SignUps::whereIn('activity_id',$act_ids)->where(['user_id'=>$user_id,'pay_state'=>2])->where('status','<>',-1)->pluck('id');
            }
            if ($order->isEmpty() && $bid->isEmpty() && $phone->isEmpty() &&( $act_ids->isEmpty() || $sign->isEmpty())){
                return response()->json(["code"=>0, "msg"=>'亲，与供应商联系或购买相应服务后才可以评价哦!']);
            }
            $ret = StoreEvaluates::where(['user_id'=>$user_id,'store_id'=>$store_id])->where('status','<>',-1)->value('id');
            if (!empty($ret)){
                return response()->json(["code"=>0, "msg"=>'您已评价过此供应商，不能再次评价!']);
            }

            $params = [
                'user_id' => $user_id,
                'user_name' => $userinfo['username'],
                'user_avatar' => $userinfo['avatar'],
                'store_id' => $store_id,
                'content' => (string)$request->post('content'),
                'speed' => (int)$request->post('speed',5),
                'quality' => (int)$request->post('quality',5),
                'attitude' => (int)$request->post('attitude',5),
            ];
            $params['store_name'] = Stores::where('id',$params['store_id'])->value('store_name');
            $params['average_star'] = intval(round(($params['speed']+$params['quality']+$params['attitude'])/3));//平均分
            if($params['average_star'] ==5 || $params['average_star'] == 4){
                $params['type'] = 1;//好评
            }elseif ($params['average_star'] ==3){
                $params['type'] = 2;//中评
            }elseif ($params['average_star'] ==2 || $params['average_star'] == 1){
                $params['type'] = 3;//差评
            }
            StoreEvaluates::create($params);
            Stores::where('id',$params['store_id'])->increment('praise');//评论量加1
            //计算好评率
            $all = StoreEvaluates::where(['store_id'=>$params['store_id']])->where('status','<>',-1)->count();
            $goods = StoreEvaluates::where(['store_id'=>$params['store_id'], 'type'=>1])->where('status','<>',-1)->count();
            $credit = $goods/$all*100;
            Stores::where('id',$params['store_id'])->update(['credit'=>$credit]);

            return response()->json(["code"=>1, "msg"=>'评价成功']);
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

}